package com.csaba.swing.action;

import java.util.logging.Level;
import java.util.logging.Logger;

import com.csaba.connector.BankService;
import com.csaba.connector.model.Session;
import com.csaba.swing.MainWindow;
import com.csaba.swing.gui.util.BusyDialog;
import com.csaba.util.LoggerHelper;

public class ServiceRunner
{
	private final static Logger logger = LoggerHelper.getDefaultLogger();

	private final BankService service;
	private final Session session;
	private final String message;
	private Exception exception;

	public ServiceRunner( final Session session, final BankService service, final String message )
	{
		this.service = service;
		this.message = message;
		this.session = session;
	}

	public void execute() throws Exception
	{
		final BusyDialog busy = new BusyDialog(MainWindow.getString("ServiceRunner.msg.communication"), message); //$NON-NLS-1$

		( new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				try
				{
					Thread.sleep(100); // sleep a bit to show up the dialog
					service.execute(session);
				}
				catch ( final Exception e )
				{
					setException(e);
				}
				finally
				{
					busy.dispose();
				}
			}
		}) ).start();

		busy.setVisible(true);
		if ( exception != null )
		{
			logger.log(Level.FINEST, "Exception caught in ansynch service invocation.", exception); //$NON-NLS-1$
			throw exception;
		}
	}

	private void setException( final Exception exception )
	{
		this.exception = exception;
	}
}
